package com.toplabs.unashu.service.impl;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.toplabs.unashu.common.utils.IPUtils;
import com.toplabs.unashu.dto.PageDto;
import com.toplabs.unashu.dto.SearchLog;
import com.toplabs.unashu.entity.LoginLog;
import com.toplabs.unashu.exception.ServiceException;
import com.toplabs.unashu.mapper.LoginLogMapper;
import com.toplabs.unashu.service.LoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ityanger
 * @since 2020-08-23
 */
@Slf4j
@Service
public class LoginLogServiceImpl implements LoginLogService {

    private final LoginLogMapper loginLogMapper;

    public LoginLogServiceImpl(LoginLogMapper loginLogMapper) {
        this.loginLogMapper = loginLogMapper;
    }

    @Override
    public void saveLoginLog(HttpServletRequest request) {
        LoginLog loginLog = new LoginLog();
        String ip = IPUtils.getIpAddr(request);
        loginLog.setIp(ip);
        loginLog.setLocation(IPUtils.getCityInfo(ip));
        // String os = OsAndBrowserUtils.getOsAndBrowserInfo(request).get("OS")
        // String browser = OsAndBrowserUtils.getOsAndBrowserInfo(request).get("BROWSER")
        String uaStr = request.getHeader("User-Agent");
        UserAgent ua = UserAgentUtil.parse(uaStr);
        String browser = ua.getBrowser().toString() + "-" + ua.getVersion();//Chrome
        String os = ua.getOs().toString();
        loginLog.setUserSystem(os);
        loginLog.setUserBrowser(browser);
        try {
            int insert = loginLogMapper.insert(loginLog);
            if (insert == 0) {
                log.error("登入日志添加失败！");
            }
        } catch (MyBatisSystemException e) {
            log.error("登入日志添加失败！");
        }
    }

    @Override
    public void delete(Long id) throws ServiceException {
        int delete = loginLogMapper.delete(id);
        if (delete == 0) {
            throw new ServiceException("要删除的日志不存在");
        }
    }

    @Override
    public PageDto<LoginLog> getLoginLogList(SearchLog searchLog) {
        log.debug("start time: {}", searchLog.getStartTime());
        log.debug("end time: {}", searchLog.getEndTime());
        searchLog.setPageNum((searchLog.getPageNum() - 1) * searchLog.getPageSize());
        List<LoginLog> logList = loginLogMapper.getLoginLogList(searchLog);
        int logTotal = loginLogMapper.getLoginLogTotal(searchLog);
        return new PageDto<>(logTotal, logList);
    }

    @Override
    public void batchDelete(List<Long> ids) throws ServiceException {
        for (Long id : ids) {
            int delete = loginLogMapper.delete(id);
            if (delete == 0) {
                throw new ServiceException("要删除的登入日志不存在");
            }
        }
    }
}
